<?php

/**
 *
 * lazy~
 */
function P($x) {
    print_r($x);
    exit;
}

/*
 * file upload rename rule
 */

function uploadName() {
    return time() . getCode();
}

function pwdHash($password, $type = 'md5') {
    return hash($type, $password);
}

function showEmpty($value){
    if($value === '' || $value === null){
        return '<small>无数据</small>';
    }
    return $value;
}

function CS( $group = '',$expire = '',  $key = ''){
    $array['cache']['set'] = true ;
    if($group) {
       $array['cache']['group'] = $group;
       if(empty($expire)) {
           $expire = 180;
       }
    }
    if($key) {
       $array['cache']['key'] = $key;
    }
    if($expire) {
       $array['cache']['expire'] = $expire;
    }
    return $array;
}

/**
 * 返回一字符串，十进制 number 以 radix 进制的表示。
 * @param dec       需要转换的数字
 * @param toRadix    输出进制。当不在转换范围内时，此参数会被设定为 2，以便及时发现。
 * @return    指定输出进制的数字
 */
function dec2Any($shu, $jinzhi) {
    $zifu = "";
    while ($shu != 0) {
        $linshi = $shu % $jinzhi;
        switch ($jinzhi) {
            case 2:
                $zifu = decbin($shu);
                return $zifu;
            case 8:
                $zifu = decoct($shu);
                return $zifu;
            case 16:
                $zifu = dechex($shu);
                return $zifu;
            case 36:
                if ($linshi >= 10) {

                    $zifu.= chr(($linshi + 55));
                } else {
                    $zifu.= $linshi;
                }
                break;
            case 62:
                if (($linshi >= 10) && ($linshi < 36)) {
                    $zifu.= chr($linshi + 55);
                    break;
                }
                if (($linshi >= 36) && ($linshi < 62)) {
                    $zifu.= chr($linshi + 61);
                    break;
                }
                $zifu.= $linshi;
                break;
            default:
                $zifu.= $linshi;
                break;
        }
        $shu = intval($shu / $jinzhi);
    }
    return strrev($zifu);
}


/**
 *
 * bug record for developing
 */
function debug($message) {
    Log::write($message, $level = 'DEBUG:', $type = '', $destination = 'debug.log', $extra = '');
}

/**
 *
 * 返回一串随机数
 * @param integer $length length of return vold
 * @param integer $mode character string 
 */
function getCode($length = 4, $mode = 0) {
    switch ($mode) {
        case '1':
            $str = '1234567890';
            break;
        case '2':
            $str = 'abcdefghijklmnopqrstuvwxyz';
            break;
        case '3':
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        default:
            $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
    }

    $result = '';
    $l = strlen($str) - 1;
    $num = 0;

    for ($i = 0; $i < $length; $i++) {
        $num = rand(0, $l);
        $a = $str[$num];
        $result = $result . $a;
    }
    return $result;
}

/**
 *
 * 利用json编码
 */
function getJson($rows, $total) {

    if (empty($rows)) {
        $rows = array();
    }
    $json['total'] = $total;
    $json['rows'] = $rows;
    return json_encode($json);
}

/**
 * 邮件发送类 PHPMailer 整合
 * @param string $to 接受邮件方
 * @param string $subject 邮件标题
 * @param string $body 邮件正文
 * @param string $altBody 邮件说明
 * @return bool 
 */
    function phpMail($to, $subject = 'Appgo', $body = '', $altBody = "Appgo") {
    vendor('PHPMailer.class#phpmailer');
    $mail = new PHPMailer(true); //New instance, with exceptions enabled
    $mail->IsSMTP();                           // tell the class to use SMTP
    $mail->SMTPAuth = true;                  // enable SMTP authentication
    $mail->Port = C('SMTP_PORT');                    // set the SMTP server port
    $mail->Host = C('SMTP_HOST'); // SMTP server
    $mail->Username = C('SMTP_USERNAME');     // SMTP server username
    $mail->Password = C('SMTP_PASSWORD');            // SMTP server password
    $mail->CharSet = "UTF-8";
    //$mail->IsSendmail();  // tell the class to use Sendmail
    $mail->SMTPDebug = 0;
    $mail->AddReplyTo(C('SMTP_REPLY'), C('SMTP_REPLY_NAME'));
    $mail->From = C('SMTP_SEND');
    $mail->FromName = C('SMTP_SEND_NAME');
    $mail->AddAddress($to, '会员您好');
    $mail->Subject = $subject;
    $mail->AltBody = $altBody; // optional, comment out and test
    $mail->WordWrap = 80; // set word wrap
    
    $mail->MsgHTML($body);
    $mail->IsHTML(true); // send as HTML
    
    if ($mail->Send()) {
        return true;
    } else {
        return false;
    }
}


/**
  +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码 
  +----------------------------------------------------------
 * @static 
 * @access public 
  +----------------------------------------------------------
 * @param string $str 需要转换的字符串 
 * @param string $start 开始位置 
 * @param string $length 截取长度 
 * @param string $charset 编码格式 
 * @param string $suffix 截断显示字符 
  +----------------------------------------------------------
 * @return string 
  +----------------------------------------------------------
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if (mb_strlen($str, $charset) <= $length)
        return $str;
    if (function_exists("mb_substr")) {
        if ($suffix)
            return mb_substr($str, $start, $length, $charset) . "...";
        else
            return mb_substr($str, $start, $length, $charset);
    }
    elseif (function_exists('iconv_substr')) {
        if ($suffix)
            return iconv_substr($str, $start, $length, $charset) . "...";
        else
            return iconv_substr($str, $start, $length, $charset);
    }
    $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    if ($suffix)
        return $slice . "…";
    return $slice;
}

function xml_decode($xml, $root = 'response') {
    $search = '/<(' . $root . ')>(.*)<\/\s*?\\1\s*?>/s';
    $array = array();
    if(preg_match($search, $xml, $matches)){
        $array = xml_to_array($matches[2]);
    }
    return $array;
}

function xml_to_array($xml) {
    $search = '/<(\w+)\s*?(?:[^\/>]*)\s*(?:\/>|>(.*?)<\/\s*?\\1\s*?>)/s';
    $array = array ();
    if(preg_match_all($search, $xml, $matches)){
        foreach ($matches[1] as $i => $key) {
            $value = $matches[2][$i];
            if(preg_match_all($search, $value, $_matches)){
                $array[$key] = xml_to_array($value);
            }else{
                if('ITEM' == strtoupper($key)){
                    $array[] = html_entity_decode($value);
                }else{
                    $array[$key] = html_entity_decode($value);
                }
            }
        }
    }
    return $array;
}

function formatChangelog($log){
    return str_replace("\n",'<br/>',$log);
}
?>
